const Koa = require('koa');
const ws = require('koa-websocket');
const app = ws(new Koa());

app.ws.use(function (ctx) {
  // 每秒钟向客户端发送当前时间
  const intervalId = setInterval(() => {
    const currentTime = new Date().toISOString();
    ctx.websocket.send(`Current time: ${currentTime}`);
  }, 1000);

  ctx.websocket.on('message', function (message) {
    console.log('Received message:', message);
    ctx.websocket.send(`Echo: ${message}`);
  });

  ctx.websocket.on('close', () => {
    console.log('WebSocket connection closed');
    clearInterval(intervalId); // 关闭连接时清除定时器
  });
});

app.listen(3403, () => {
  console.log('WebSocket server listening on port 3403');
});
